const osmosis = require('osmosis');
const cron = require('node-cron');
const db = require("./db")
const format = require('string-format')

format.extend(String.prototype, {})

const monitorCoins = ["XSD", "TRTT"]
var lastUpdatedDate = {}

function updateMNStatus(coinSymbol) {
    osmosis
        .get("https://mncn.online/coins/" + coinSymbol)
        .find('.card:eq(8)')
        .set({
            'activatedMN': 'li:eq(2) span',
            'ROI': 'li:eq(0) span',
            'UpdatedDate': '.sys-msg'
        })
        .find('.card:eq(7)')
        .set({
            'Price': 'li:eq(2) span'
        })
        .data(function (item) {

            updated = new Date(item.UpdatedDate.match(/\d{4}\-\d{2}\-\d{2}\s+\d{2}:\d{2}/).toString())

            if (updated.getTime() <= lastUpdatedDate[coinSymbol].getTime()) {
                return
            }

            lastUpdatedDate[coinSymbol] = updated
            var status = db.insertMNStatus(coinSymbol,
                item.activatedMN.replace(",", ""),
                item.ROI.replace("/ ", ""),
                item.Price,
                updated)

            console.log("Insert status, [COIN Name]:{0} [Activated MN]: {1}".format(coinSymbol, item.activatedMN))
        })
}

async function test() {
    await db.test()
}

//test()

//init data

async function startMNStatusMonitor() {
    for (index in monitorCoins) {
        var item = monitorCoins[index]
        var last = await db.queryLastItemByDateDesc(item)
        if (last != undefined && last.length > 0) {
            lastUpdatedDate[item] = last[0].Updated
        } else {
            lastUpdatedDate[item] = new Date()
        }
    }
    console.log("updating masternode status...")
    var task = cron.schedule('* * * * *', async () => {
        //console.log("updating masternode status...")
        monitorCoins.forEach(function (item) {
            updateMNStatus(item)
        })
        //console.log("wait to next minute")
    }, {
        scheduled: false,
    });

    task.start()
    return task
}

module.exports = {
    "startMNStatusMonitor": startMNStatusMonitor
}